<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Http\Requests\Admin\BaseRequest;
use App\Models\Admin\GoodsNonstandard;
use App\Models\Admin\Goods;
use App\Models\Admin\GoodsCategory;
use App\Models\Admin\GoodsDatum;
use App\Models\Admin\GoodsDetail;
use App\Models\Admin\GoodsImage;
use App\Models\Admin\GoodsNonstandardSpu;
use App\Models\Admin\GoodsSpu;
use App\Models\Admin\GoodsStandard;
use App\Models\Admin\GoodsStandardName;
use App\Models\Admin\GoodsStandardSpu;
use Illuminate\Http\Request;
use Auth,DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class GoodsNonstandardController extends AdminController
{
    use AdminTrait;

    protected $model;
    protected $unique_id = '';
    protected $type_brand = 4;

    public function __construct(GoodsNonstandard $model)
    {
        parent::__construct();
        $this->model = $model;
    }

    /**
     * 定义验证规则
     * @var []
     */
    protected $validate_rule = [
        'category_id' => 'required|integer|min:1',
        'pinyin' => 'nullable|alpha',
    ];

    /**
     * 定特殊的验证规则
     */
    protected function rules()
    {

        return [
            'name' => [
                'required',
                Rule::unique('goods_standard')->ignore($this->unique_id),
            ],
            'goods_code' => [
                'nullable',
                Rule::unique('goods')->ignore($this->unique_id),
            ],
        ];
    }

    protected $err_msg = [
        'name.required' => '名称不能为空',
        'name.unique' => '该商品已存在',
        'goods_code.unique' => '商品编码已存在',
        'category_id.min' => '请选择商品的二级分类',
        'pinyin.alpha' => '关键词必须全部为字母',
    ];

    protected $statusList = [
        0 => '下架',
        1 => '上架',
    ];

    protected $standardList = [
        0 => '非标品',
        1 => '标品',
    ];

    protected $recommendList = [
        0 => '否',
        1 => '是',
    ];


    protected function search($request)
    {
        $select = $this->model->with(['spu' => function ($query) {
            $query->with(['spuName', 'spuUnit']);
        }, 'category', 'category_p', 'goods']);

        $pid = $request->query('pid');
        $category_id = $request->query('category_id');
        if ($category_id) {
            $select = $select->where('category_id', $category_id);
        } else if ($pid) {
            $select = $select->where('pid', $pid);
        }

        if ($name = $request->query('name')) {
            $select = $select->where(function ($query) use ($name) {
                $query->orWhere('name', 'like', "%$name%")->orWhere('pinyin', 'like', "%$name%")->orWhere('goods_code', 'like', "%$name%");
            });
        }
        $is_standard = $request->query('is_standard');
        if(!is_null($is_standard))
        {
            $select = $select->where('is_standard',$is_standard);
        }

        return $select;
    }

    protected function beforeIndex()
    {
        $categoryList = GoodsCategory::getCategorys();
        //返回品牌数据
        $brand = GoodsDatum::getDatum($this->type_brand);

        return ['categoryList' => $categoryList, 'brand_list' => $brand];
    }

    protected function setRequestField($arr, $type = false)
    {
        //过滤字段
        if (isset($arr['_token'])) unset($arr['_token']);
        if (isset($arr['list'])) unset($arr['list']);
        if (isset($arr['purchase_relation'])) unset($arr['purchase_relation']);
        if (isset($arr['sign'])) unset($arr['sign']);
        if (isset($arr['timeStamp'])) unset($arr['timeStamp']);
        return $arr;
    }

    public function baseData(BaseRequest $request)
    {
        $categoryList = GoodsCategory::getCategorys();

        //返回品牌数据
        $brand = GoodsDatum::getDatum($this->type_brand);
        $unit = GoodsDatum::getDatum(1);
        $tag = GoodsDatum::getDatum(2);
        $attribute = GoodsDatum::getDatum(3);
        return response()->json(['errcode' => 0, 'data' => ['category' => $categoryList, 'unit' => $unit, 'tag' => $tag, 'attribute' => $attribute, 'brand' => $brand], 'errmsg' => "ok"]);
    }

    protected function afterData($info, $requestData, $perInfo = null, $nextInfo = null)
    {
        //编辑
        if (isset($requestData['id'])) {
            $attr = json_decode($requestData['list'], true);
            foreach ($attr as $k => $v) {
                if (isset($v['id']) && $v['id']) {
                    $save = GoodsNonstandardSpu::find($v['id']);
                    foreach ($v as $kk => $vv) {
                        $save->$kk = $vv;
                    }
                    $save->save();
                } else {
                    $v['goods_nonstandard_id'] = $info->id;
                    GoodsNonstandardSpu::create($v);
                }
            }
            //判断是否要更改用户的商品表
        }
    }


    public function info(BaseRequest $request)
    {
        try {
            $id = $request->id;
            if (!is_numeric($id)) {
                return response()->json(['errcode' => 40016, 'errmsg' => '参数错误']);
            }
            $info = $this->model->with(['spu' => function ($query) {
            }])->findOrFail($id);

            return response()->json(['errcode' => 0, 'data' => ['info' => $info->toArray()], 'errmsg' => 'ok']);
        } catch (\Exception $exception) {
            return response()->json(['errcode' => 40009, 'errmsg' => '信息不存在']);
        }
    }

    public function checkName(BaseRequest $request)
    {
        $name = $request->all('name', '');
        $flag_1 = GoodsNonstandard::where('name', $name)->count();
        if ($flag_1) {
            return response()->json(['errcode' => '40020', 'errmsg' => '商品已存在']);
        }
        return response()->json(['errcode' => '0', 'errmsg' => 'ok']);
    }

    private function checkSkuCode($id,$code)
    {
        $flag = GoodsStandardSpu::where('id','!=',$id)
            ->where('standard_spu_code',$code)
            ->count();
        if ($flag){
            return $this->error(['40065','sku编码必须唯一']);
        }
        return [];
    }

    public function createSpu($request)
    {
        $category_id=isset($request['category_id'])?$request['category_id']:0;
        $code_category=GoodsCategory::where('id',$category_id)->value('code');
        if(!$code_category) return false;
        $spu_max=GoodsStandard::where('category_id',$category_id)->max('standard_code');
        if(is_null($spu_max))
        {
            $spu=$code_category.'001';
        }
        else
        {
            $spu=(string)($spu_max+1);
            $spu=strlen($spu)==6?'0'.$spu:$spu;
        }
        return $spu;
    }

    public function createSku($info)
    {
        $standard_id=$info->id;
        $spu=$info->standard_code;
        $sku_max=GoodsStandardSpu::where('standard_goods_id',$standard_id)->max('standard_spu_code');
        if(is_null($sku_max))
        {
            $sku='C'.$spu.'10';
        }
        else
        {
            $sku_max_num=substr($sku_max,1);
            $sku_num=(string)($sku_max_num+1);
            $sku_num=strlen($sku_num)==8?'0'.$sku_num:$sku_num;
            $sku='C'.$sku_num;
        }
        return $sku;
    }

    //导入标准库
    public function importStandard(BaseRequest $request)
    {
        $input = $request->only('name_list','txa_code','id', 'category_id', 'pid', 'brand', 'pinyin', 'describe', 'detail', 'pic', 'pics', 'is_standard', 'transfer', 'list');
        //过滤数据
        $rules = [
            'id' => 'required|exists:goods_nonstandard,id',
            'category_id' => 'required|exists:goods_category,id',
            'pid' => 'required|exists:goods_category,id',
            'brand' => 'integer|nullable',
            'pinyin' => 'nullable|alpha',
            'describe' => 'string|nullable',
            'detail' => 'string|nullable',
            'pic' => 'string|nullable',
            'pics' => 'string|nullable',
            'is_standard' => 'required|in:0,1',
            'transfer' => 'required|in:0,1',
            'list' => 'required|string',
            'txa_code' => 'nullable|string',
            'name_list' => 'nullable|string',
        ];
        $msg=[
          'pinyin.alpha'=>'助记码必须为字母',
        ];
        $validator = Validator::make($input, $rules, $msg);
        if ($validator->fails())
            return $this->error(['-1', $validator->errors()->first()]);
        $non_standard_id = $input['id'];
        $standard_code_new = $this->createSpu($input);
        if($standard_code_new===false)
        {
            return response()->json(['errcode'=>'-1','errmsg'=>'商品分类不存在']);
        }

        $insert_data = $input;
        //去获取数据库
        $name_db=GoodsNonstandard::where('id',$non_standard_id)->value('name');
        if(!$name_db)
        {
            return $this->error();
        }
        $name_uqi=GoodsStandard::where('name',$name_db)->count();
        if($name_uqi)
        {
            return $this->error(['-1','商品名称在标准库已存在']);
        }
        $insert_data['name']=$name_db;
        unset($insert_data['id']);
        unset($insert_data['list']);
        if(isset($insert_data['name_list']))
        {
            unset($insert_data['name_list']);
        }
        $insert_data['standard_code']=$standard_code_new;
        DB::beginTransaction();
        try {
            $info_standard=GoodsStandard::create($insert_data);
            $standard_goods_id=$info_standard->id;
            if(isset($input['name_list']))
            {
                $name_list = explode(',',$input['name_list']);
                $name_list=empty($name_list[0])?[]:$name_list;
                GoodsStandardName::addNames($standard_goods_id,$name_list);
            }

            $list = json_decode($input['list'], true);
            foreach ($list as $k => $v) {
                $v['standard_goods_id']=$standard_goods_id;
                $spu_code_new=$this->createSku($info_standard);
                $v['standard_spu_code']=$spu_code_new;
                unset($v['goods_spu_code']);
                if(isset($v['id']))
                {
                    $non_spu_id=$v['id'];
                    unset($v['id']);
                }
                $standard_spu_id=GoodsStandardSpu::add($v);
                if(isset($non_spu_id))
                {
                    $data_goods_spu=[
                        'goods_spu_code'=>'',
                        'standard_spu_code'=>$spu_code_new,
                        'nonstandard_spu_id'=>0,
                        'standard_spu_id'=>$standard_spu_id,
                    ];
                    GoodsSpu::where('nonstandard_spu_id',$non_spu_id)->update($data_goods_spu);
                }
            }
            GoodsNonstandard::where('id',$non_standard_id)->delete();
            GoodsNonstandardSpu::where('goods_nonstandard_id',$non_standard_id)->delete();
            $data_goods=[
                'goods_code'=>'',
                'standard_code'=>$standard_code_new,
                'nonstandard_goods_id'=>0,
                'standard_goods_id'=>$standard_goods_id,
            ];
            Goods::where('nonstandard_goods_id',$non_standard_id)->update($data_goods);

            if (method_exists($this->model,'addLog')){
                $this->model->addLog(['name'=>$name_db,'id'=>$input['id']],[],6,'import');
            }
            DB::commit();
            return $this->success();
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
//            return $exception->getMessage();
            return $this->error();
        }
    }


}
